<?php
namespace Icsoc\DataBundle\Model;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 下面中用到info参数的json格式大概为 ；filter搜素(具体提供搜素字段各个接口不一样)，
 *  pagination分页(rows 每页显示条数,page第几页)，sort排序
 *  {"pagination":{"rows":20,"page":"5"},"filter":{"endresult":"0"},"sort":{"field":"id","order":"desc"}}
 * Class BillModel
 * @package Icsoc\DataBundle\Model
 *
 */
class BlackModel extends BaseModel
{

    /** @var \Symfony\Component\DependencyInjection\Container  */
    public $container;

    /** @var \Doctrine\DBAL\Connection  */
    private $dbal;

    //分机类型
    private $phoneType;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->dbal = $this->container->get('doctrine.dbal.default_connection');
        $this->phoneType = $this->container->getParameter('phone_type');
    }

    /**
     * 黑名单列表
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,// json 提供分页信息
     *                     )
     * @return array
     */
    public function getBlackList(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $this->purifyHtml($param['vcc_code']);
        $info = empty($param['info']) ? '' : $this->purifyHtml($param['info']);

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message'=>'info格式非json');
            }
        }
        $where = '';
        if (isset($addInfo['filter'])) {
            $types = $this->container->get('icsoc_core.common.class')->getBlacTypes($vid);
            if (isset($addInfo['filter']['keyword']) && !empty($addInfo['filter']['keyword'])) {
                $where.=" AND (phone_num  LIKE '%".$addInfo['filter']['keyword']."%'
                OR trunk_num LIKE '%".$addInfo['filter']['keyword']."%' ) ";
            }
            if (isset($addInfo['filter']['select_type']) && !empty($addInfo['filter']['select_type'])
                && isset($types[$addInfo['filter']['select_type']])) {
                $where.=" AND call_type = '".intval($addInfo['filter']['select_type'])."'";
            } else {
                if (count($types) == 1) {
                    $where.=" AND 0 = 1 ";
                } elseif (count($types) >=2 && count($types) < 3) {
                    //说明有一个禁用
                    $callType = isset($types[1]) ? 1 : 2;
                    $where.=" AND call_type = '".$callType."'";
                } else {
                    $where.='';
                }
            }
        }
        $count = $this->dbal->fetchColumn(
            "SELECT count(*)
            FROM cc_blacklist
            WHERE vcc_id = :vid ".$where,
            array('vid'=>$vid)
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'cc_blacklist', $addInfo);
        $data = $this->dbal->fetchAll(
            "SELECT id,vcc_id,phone_num,black_type,trunk_num,call_type,handle_name,handle_time,remark FROM cc_blacklist WHERE vcc_id= :vid ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vid'=>$vid)
        );
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'page' => $page['page'],
            'totalPage'=>$page['totalPage'],
            'data' => $data
        );
        return $ret;
    }

    /**
     * 删除黑名单
     * @param array $param vcc_id 企业id或者 vcc_code 企业代码， ids 删除的id 多个用,隔开（1,2,3）
     * @return array|string
     */
    public function delBlack(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $this->purifyHtml($param['vcc_code']);
        $phone_ids = empty($param['ids']) ? '' : $this->purifyHtml(is_string($param['ids']) ? $param['ids'] : '');

        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($phone_ids)) {
            $ret = array(
                'code' => 403,
                'message' => '号码ID为空'
            );
            return $ret;
        }

        $this->dbal->beginTransaction();
        $phonesArray = explode(',', $phone_ids);
        $logStr = "";
        foreach ($phonesArray as $phone_id) {
            if (!is_numeric($phone_id)) {
                $ret = array(
                    'code' => 404,
                    'message' => '号码ID中包含非数字字符'
                );

                return $ret;
            }
            $data = array(
                'vcc_id' => $vcc_id,
                'id' => $phone_id,
            );
            $logStr.=$data['id'].',';
            $this->dbal->delete('cc_blacklist', $data);
        }
        try {
            $this->dbal->commit();
            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );
            if (!empty($logStr)) {
                $logStr = $this->container->get('translator')
                    ->trans('Delete black list %str%', array('%str%'=>$logStr));
                $this->container->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            }
            return $ret;
        } catch (Exception $e) {
            $this->dbal->rollback();
            $ret = array(
                'code' => 405,
                'message' => '删除黑名单失败['.$e->getMessage().']'
            );

            return $ret;
        }
    }

    /**
     * @param array $param
     *      vcc_id 企业id或者
     *      vcc_code 企业代码，
     *      phones array黑名单号码，
     *      black_type 电话类型（1，固定值，2，模糊匹配）
     *      trunk_num  中继号码；空为所有，
     *      call_type  黑名单类型；（1，呼入，2，呼出），
     * @return array|string
     *
     */
    public function blacklistAdd(array $param = array())
    {
        $vcc_id = isset($param['vcc_id']) && !empty($param['vcc_id']) ? $param['vcc_id'] : 0;
        $vcc_code = isset($param['vcc_code']) && !empty($param['vcc_code']) ? $param['vcc_code'] : 0;
        $phones = isset($param['phones']) && !empty($param['phones']) ? $param['phones'] : array();
//        $phone_type = isset($param['phone_type']) && !empty($param['phone_type']) ? $param['phone_type'] : 1;
        $trunk_num = isset($param['trunk_num']) && !empty($param['trunk_num']) ? $param['trunk_num'] : '';
        $call_type = isset($param['call_type']) && !empty($param['call_type']) ? $param['call_type'] : 1;
        $black_type = isset($param['black_type']) && !empty($param['black_type']) ? $param['black_type'] : 1;
        $remark = isset($param['remark']) && !empty($param['remark']) ? $param['remark'] : '';
        $handleName = isset($param['handle_name']) && !empty($param['handle_name']) ? $param['handle_name'] : '';

        if (empty($vcc_id)) {
            $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
        } else {
            if (!is_numeric($vcc_id)) {
                $ret = array(
                    'code' => 409,
                    'message' => '企业ID包含非数字字符',
                );
                return $ret;
            }
            //判断企业ID 是否存在；
            $vcc_code =$this->dbal->fetchColumn(
                "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id = :vcc_id",
                array('vcc_id' => $vcc_id)
            );
            if (empty($vcc_code)) {
                $ret = array(
                    'code' => 410,
                    'message' => '企业ID不存在',
                );
                return $ret;
            }
        }
        if (empty($phones)) {
            $ret = array(
                'code' => 411,
                'message' => '号码为空'
            );
            return $ret;
        }

        if (!is_array($phones)) {
            $ret = array(
                'code' => 406,
                'message' => '号码格式不对'
            );
            return $ret;
        }
        if (!empty($trunk_num)) {
            //查看中继号是否存在
            $count = $this->dbal->fetchColumn(
                'SELECT count(*) FROM cc_phone400s WHERE vcc_id = :vcc_id AND phone = :phone ',
                array('vcc_id'=>$vcc_id, 'phone'=>$trunk_num)
            );
            if ($count <= 0) {
                return array('code'=>408, 'message'=>'中继号码不存在');
            }
        }
        $this->dbal->beginTransaction();
        foreach ($phones as $key => $val) {
            $phones[$key] = trim($val);
        }
        $phones = array_unique($phones);
        $logStr = '';
        foreach ($phones as $phone) {
            switch ($black_type) {
                case '1'://固定号码
                    if (!is_numeric(trim($phone))) {
                        $ret = array(
                            'code' => 403,
                            'message' => '固定号码中包含非数字字符'
                        );
                        return $ret;
                    }
                    break;
                case '2'://模糊匹配
                    if (!preg_match('/^[\*0-9]+?$/', trim($phone))) {
                        $ret = array(
                            'code' => 407,
                            'message' => '模糊匹配号码中包含除*外的非数字字符'
                        );
                        return $ret;
                    }
                    break;
                default:
                    break;
            }
            $data = array(
                'vcc_id' => $vcc_id,
                'phone_num' => $phone,
                'trunk_num' => $trunk_num,
                'call_type' => $call_type,
                'black_type' => $black_type,
            );
            $count = $this->dbal->fetchColumn(
                "SELECT count(*) FROM cc_blacklist
                 WHERE vcc_id = :vcc_id AND phone_num = :phone_num AND black_type = :black_type AND trunk_num = :trunk_num
                 AND call_type = :call_type
                 ",
                $data
            );
            if ($count) {
                continue;
            }
            $logStr.=$data['phone_num'].',';
            $data['remark'] = $remark;
            $data['handle_time'] = time();
            $data['handle_name'] = $handleName;
            $this->dbal->insert('cc_blacklist', $data);
        }

        try {
            $this->dbal->commit();
            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );
            if (!empty($logStr)) {
                $logStr = $this->container->get('translator')->trans('Add black list %str%', array('%str%'=>$logStr));
                $this->container->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
            }
            return $ret;
        } catch (Exception $e) {
            $this->dbal->rollback();
            $ret = array(
                'code' => 404,
                'message' => '添加黑名单失败['.$e->getMessage().']'
            );
            return $ret;
        }
    }
}
